const chokidar = require('chokidar');
const fse = require('fs-extra');
const log4js = require('log4js');
const moment = require('moment');

// watched directory
const watchedDir = 'c:\\test\\';
// target directory for copying
const targetBaseDir = 'C:\\target\\';

let watcherReady = false;

/* Config Logger */
log4js.configure({
  appenders: {
    out: { type: 'stdout' },
    app: { type: 'file', filename: `app.${moment().format('Y-M-DTH-m')}.log` }
  },
  categories: {
    default: { appenders: [ 'out', 'app' ], level: 'debug' },
    app: { appenders: [ 'app' ], level: 'info'}
  }
});
const logger = log4js.getLogger('app');

/* Copy file and dirs */
let copy = (event, path) => {
  if (!watcherReady) { // don't act on start event;
    return;
  }
  let targetDir = targetBaseDir + path.replace(watchedDir, '');  
  logger.info(`${event} detected and copy from "${path}" to "${targetDir}"`);
  fse.copy(path, targetDir, {overwrite: true}).catch(error => {
    logger.error(error);
  });
}

let watcher = chokidar.watch(watchedDir);

watcher.on('ready', () => {
  logger.info('App is ready');
  watcherReady = true;
});

watcher.on('add', path => copy('add', path))
       .on('change', path => copy('change', path))
       .on('addDir', path => copy('addDir', path));
